<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

return (function () {
    $config = require __DIR__ . '/bai/config.php';

    $autoload = 'autoload';
    if (empty($config[$autoload]['include'])) {
        http_response_code(500);
        return null;
    }
    $methods = $config['methods'] ?? [];
    if ($methods && !in_array($_SERVER['REQUEST_METHOD'], $methods)) {
        http_response_code(400);
        return null;
    }
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if (preg_match('/\\.([a-zA-Z0-9]+)$/', $path, $matches)) {
        $hosting = $config['hosting'] ?? [];
        if ($hosting && !in_array($matches[1], $hosting)) {
            http_response_code(400);
            return null;
        }
    }

    $cacheFile = $config[$autoload]['cache'] ?? __DIR__ . "/resources/caches/{$autoload}.php";
    if (defined('DEV') || !is_file($cacheFile)) {
        require_once __DIR__ . '/bai/feature/Files.php';
        $map = [];
        $action = function (string $file, string $path, array &$result)
        {
            if (!preg_match('/\\.php$/i', $file)) return;
            $content = file_get_contents($path);
            $spaceName = '';
            if (preg_match('/\\snamespace\\s+([a-zA-Z0-9_\\\\\\x80-\\xff]+)[\\s;]/im', $content, $spaceMatchs)) {
                $spaceName = $spaceMatchs[1] . '\\';
            }
            if (preg_match_all('/\\s(?:class|interface|trait)\\s+([a-zA-Z0-9_\\x80-\\xff]+)[\\s{]/im', $content, $classMatchs)) {
                foreach ($classMatchs[1] as $className) {
                    $result["{$spaceName}$className"] = $path;
                    $result[$className][] = "{$spaceName}$className";
                }
            }
        };
        foreach ($config[$autoload]['include'] as $dir) {
            $map = array_merge_recursive($map, \bai\feature\Files::scanFiles($dir, $action));
        }
        $content = \bai\feature\Files::toPhp($map);
        file_put_contents($cacheFile, $content);
    }
    $config[$autoload]['map'] = require $cacheFile;

    spl_autoload_register(function ($className) use ($config, $autoload) {
        $path = $config[$autoload]['map'][$className] ?? null;
        if (!$path || !is_string($path) || !is_file($path)) return false;
        require_once $path;
        return class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false);
    });

    $GLOBALS['config'] = $config;
    return $config;
})();
